<template>
  <div class="product-size">
    <div
      v-if="!defaultValue"
      class="control-box">
      <label class="label">
        是否启用多规格
      </label>
      <el-switch
        v-model="openStatus"
        :active-value="1"
        :inactive-value="0"
        active-color="#2362fb" />
    </div>

    <template v-if="!defaultValue && openStatus">
      <el-table
        :data="sizeList"
        :max-height="300"
        border
        style="width: 100%">
        <el-table-column
          type="index"
          align="center"
          width="55" />
        <el-table-column
          label="规格名称"
          width="115"
          header-align="left"
          align="center">
          <template slot-scope="scope">
            <el-input
              :ref="`sizeName${scope.$index}`"
              v-model="scope.row.name"
              :maxlength="100"
              class="input-new-size"
              autofocus />
          </template>
        </el-table-column>
        <el-table-column label="规格值">
          <template slot-scope="scope">
            <el-tag
              v-for="(tag, tagIndex) in scope.row.tagList"
              :key="tagIndex"
              :disable-transitions="false"
              closable
              size="small"
              @close="handleRemoveTag(tagIndex, scope.$index)">
              {{ tag }}
            </el-tag>
            <el-input
              v-if="inputShowIndex === scope.$index"
              v-model="inputTagName"
              :ref="`tagInput${scope.$index}`"
              :maxlength="100"
              class="input-new-tag"
              autofocus
              @keyup.enter.native="handleTagAdd"
              @blur="handleTagAdd" />
            <el-button
              v-else
              icon="el-icon-plus"
              class="button-new-tag"
              size="mini"
              @click="handleToTagAdd(scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleRemoveSize(scope.$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="add-column">
        <el-button
          type="text"
          @click="handleAddSize">
          + 添加规格
        </el-button>
      </div>
    </template>

    <el-table
      v-if="showProductTableEl"
      :data="productList"
      border
      class="product-table"
      style="width: 100%;">
      <el-table-column
        type="index"
        align="center"
        width="55" />
      <el-table-column label="产品主图" width="100">
        <template slot-scope="scope">
          <div
            v-if="!scope.row.img"
            class="upload-hook"
            @click="handleToUpload(scope.$index)">
            <i class="el-icon-plus" />
          </div>
          <adapter-image
            v-else
            :src="scope.row.img.url"
            class="upload-img"
            @click="handleToUpload(scope.$index)" />
        </template>
      </el-table-column>
      <el-table-column v-if="openStatus" label="规格" prop="spDataValue" />
      <el-table-column v-else label="规格">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.spDataValue"
            :maxlength="100"
            size="mini"
            autofocus />
        </template>
      </el-table-column>
      <el-table-column label="编码" width="260">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.spDataCode"
            :maxlength="100"
            :placeholder="autoNumber ? '根据编号规则自动生成，支持手动输入' : ''"
            size="mini"
            autofocus />
        </template>
      </el-table-column>
      <el-table-column
        v-if="!defaultValue"
        label="操作"
        width="80">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleRemoveProduct(scope.$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <input
      v-if="showUpLoadEl"
      ref="imgInput"
      accept="image/*"
      type="file"
      class="file-input"
      @change="upLoad">
  </div>
</template>

<script>
import {
  adminFileUploadAPI
  // adminFileDeleteByIdAPI
} from '@/api/admin/file'
import { objDeepCopy } from '@/utils'
import AdapterImage from '../../AdapterImage'

export default {
  name: 'ProductSize',
  components: {
    AdapterImage
  },
  props: {
    value: {
      type: Object,
      default: () => {}
    },
    defaultValue: {
      type: Object,
      default: null
    },
    autoNumber: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      openStatus: 0,

      sizeList: [], // 产品规格
      inputShowIndex: null,
      inputTagName: '',

      showProductTableEl: true,

      showUpLoadEl: true,
      uploadIndex: null,
      productList: [] // 产品信息
    }
  },
  computed: {
    form() {
      const jxcProductSpecificationsDataList = this.productList.map((item, index) => {
        const obj = objDeepCopy(item)
        if (obj.hasOwnProperty('img')) {
          delete obj.img
        }
        if (!obj.hasOwnProperty('spDataSort')) {
          obj.spDataSort = index
        }
        // console.log('obj:', obj)
        return obj
      })
      if (this.openStatus !== 1) {
        return {
          jxcProductSpecificationsList: [],
          jxcProductSpecificationsDataList: jxcProductSpecificationsDataList,
          openStatus: this.openStatus
        }
      }

      // const sizeList = this.defaultValue ? [] : this.sizeList
      return {
        jxcProductSpecificationsList: this.sizeList.map((item, index) => {
          const obj = objDeepCopy(item)
          delete obj.name
          delete obj.tagList
          return {
            ...obj,
            // batchId: null,
            // specificationsId: item.id || null,
            specificationsName: item.name,
            specificationsValue: item.tagList ? item.tagList.join(',') : '',
            specificationsSort: index
          }
        }),
        jxcProductSpecificationsDataList: jxcProductSpecificationsDataList,
        openStatus: this.openStatus
      }
    }
  },
  watch: {
    sizeList: {
      handler() {
        this.productList = this.generateProduct()
        if (this.productList.length > 250) {
          this.$message.error('多规格产品不能超过250条')
          if (this.inputShowIndex && this.inputTagName) {
            this.sizeList[this.inputShowIndex].tagList.splice(-1, 1)
          }
        }
        this.inputShowIndex = null
        this.inputTagName = ''
      },
      deep: true,
      immediate: true
    },
    form: {
      handler(val) {
        this.$emit('input', val)
      },
      deep: true,
      immediate: true
    },

    defaultValue: {
      handler(val) {
        if (val && val.jxcProductSpecificationsData) {
          // this.sizeList = []
          const data = objDeepCopy(val.jxcProductSpecificationsData)
          if (data.hasOwnProperty('batchId')) {
            delete data.batchId
          }
          if (data.hasOwnProperty('companyId')) {
            delete data.companyId
          }
          this.productList = [data]
          console.log('product: ', this.productList)
          this.openStatus = 1
        } else {
          this.productList = [{
            img: null,
            spDataCode: null,
            spDataValue: null
          }]
          this.openStatus = 0
        }
      },
      deep: true,
      immediate: true
    },

    openStatus: {
      handler() {
        if (this.openStatus) {
          this.productList = this.generateProduct()
        } else {
          this.productList = [{
            img: null,
            spDataCode: null,
            spDataValue: null
          }]
        }
        this.showProductTableEl = false
        this.$nextTick(() => {
          this.showProductTableEl = true
        })
      },
      deep: true
    }
  },
  methods: {
    /**
     * 删除规格
     * @param index
     */
    handleRemoveSize(index) {
      this.sizeList.splice(index, 1)
    },
    /**
     * 添加规格
     */
    handleAddSize() {
      this.sizeList.push({
        name: '',
        tagList: []
      })
      this.$nextTick(() => {
        this.$refs[`sizeName${this.sizeList.length - 1}`].focus()
      })
    },

    /**
     * 删除规格值
     * @param tagIndex
     * @param rowIndex
     */
    handleRemoveTag(tagIndex, rowIndex) {
      const tagList = this.sizeList[rowIndex].tagList
      tagList.splice(tagIndex, 1)
    },

    /**
     * 添加规格值输入框
     * @param index
     */
    handleToTagAdd(index) {
      this.inputShowIndex = index
      this.$nextTick(() => {
        this.$refs[`tagInput${index}`].focus()
      })
    },
    /**
     * 添加规格
     */
    handleTagAdd() {
      console.log('sizeList: ---', this.sizeList)
      const tagList = this.sizeList[this.inputShowIndex].tagList
      if (!tagList.includes(this.inputTagName) && this.inputTagName) {
        tagList.push(this.inputTagName)
      }
    },

    /**
     * 根据规格自动生成产品
     */
    generateProduct() {
      if (this.sizeList.length === 0) {
        return []
      }
      let arr = [[]]
      this.sizeList.forEach(sizeItem => {
        const arr0 = []
        arr.forEach(item => {
          sizeItem.tagList.forEach(o => {
            arr0.push(item.concat(o))
          })
        })
        arr = arr0
      })
      // console.log(arr)

      const sizeKey = this.sizeList.map(o => o.name)
      return arr.map(o => {
        let str = ''
        sizeKey.forEach((key, index) => {
          str = str + `${key}:${o[index]};`
        })
        return {
          spDataValue: str,
          spDataCode: ''
        }
      })
    },

    handleRemoveProduct(index) {
      this.productList.splice(index, 1)
    },

    handleToUpload(index) {
      this.uploadIndex = index
      this.$refs.imgInput.click()
    },
    upLoad(event) {
      const files = Array.from(event.target.files)

      this.$wkUploadFile.upload({
        request: adminFileUploadAPI,
        file: files[0]
      }).then(data => {
        const { res } = data
        this.productList[this.uploadIndex].spDataPicture = res.data.batchId
        this.productList[this.uploadIndex].img = res.data
        this.$set(this.productList, this.uploadIndex, this.productList[this.uploadIndex])
        this.uploadIndex = null
        this.showUpLoadEl = false
        this.$nextTick(() => {
          this.showUpLoadEl = true
        })
        this.loading = false
      }).catch(() => {})
    }
  }
}
</script>

<style scoped lang="scss">
.el-tag {
  margin: 3px 10px 3px 0;
  vertical-align: middle;
}
.button-new-tag {
  height: 24px;
  vertical-align: middle;
  padding-top: 0;
  padding-bottom: 0;
  margin: 3px 0 3px -4px;
}
.input-new-tag, .input-new-size {
  width: 90px;
  height: 24px;
  line-height: 24px;
  vertical-align: middle;
  margin: 3px 0;

  /deep/ .el-input__inner {
    height: 24px;
    line-height: 24px;
    font-size: 12px;
  }
}

.product-size {
  padding: 0 15px;
  .control-box {
    margin-bottom: 15px;
    .label {
      margin-right: 10px;
    }
  }

  .add-column {
    border: 1px solid #EBEEF5;
    border-top: 0 none;
    padding-left: 50px;
  }

  .product-table {
    margin: 15px 0;
    .upload-hook {
      width: 60px;
      height: 40px;
      text-align: center;
      line-height: 40px;
      border: 1px dashed $xr-border-color-base;
      border-radius: $xr-border-radius-base;
      margin: 5px 0;
      cursor: pointer;
      .el-icon-plus {
        font-size: 16px;
        color: #ccc;
      }
    }

    .upload-img {
      // width: 60px;
      // max-height: 100px;
      margin: 5px 0;
    }

    .input-code {
      width: 170px;
    }
  }
}

.file-input {
  width: 0;
  height: 0;
  visibility: hidden;
}
</style>
